//
//  WSOrderAllViewController.m
//  FD
//
//  Created by Yasin on 2018/10/23.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//  全部
//  代码不可控tableView 适配问题。

#import "WSOrderBaseViewController.h"
#import "WSOrderCell.h"
//view 默认隐藏
#import "FDNowDataView.h"
#import "FDPaytypeAlertTool.h" //支付弹框 封装

//controller
#import "WSPayUrlViewController.h" //支付
#import "EvaluateController.h" //评价
#import "WSZaiLaiYiDanViewController.h" //再来一单

//vendor
#import <MJRefresh.h>

@interface WSOrderBaseViewController ()<UITableViewDelegate,UITableViewDataSource>

/**标记请求参数:*/
@property (nonatomic, strong) NSArray *stateRequestParameter;
/**没有数据 默认隐藏 */
@property (nonatomic, strong) FDNowDataView *nodateView;

/***1-23转菊花防止按钮重复点击还是有问题 写成全局的*/
@property (nonatomic, strong) MBProgressHUD *hud;

@end

@implementation WSOrderBaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}

- (void)setupUI {
    [self.view addSubview:self.tableView];
    
    self.tableView.tableFooterView = [UIView new];

    //11-24
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 100, 0);
    //    [self loadOrderDataWithStatus:nil]; //请求数据 nil 表示全部数据
  
    //这里有个坑.添加到tableView上回有问题。
    //直接添加到self.view会阻断响应者链条
    //解决办法:添加到view上。放中间,高度30.确保上面可以下拉就行了。
    [self.view addSubview:self.nodateView];
    [self.nodateView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.centerY.equalTo(self.view.mas_centerY).offset(-40);
        make.height.mas_equalTo(30);
    }];
    self.nodateView.hidden = YES; //显示没有数据
    
    //下来刷新、上拉加载
    [self addTableViewRefresh];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    CGFloat bottom = Height_TabBar;
    FDLog(@"bottom:%f",bottom);
}

/// 添加下拉刷新
- (void)addTableViewRefresh {
    
    FDRefreshHader *refreshHeader = [FDRefreshHader headerWithRefreshingTarget:self refreshingAction:@selector(loadOrderDataWithStatus:)];
    self.tableView.mj_header = refreshHeader;
    //[weakSelf loadOrderDataWithStatus:self.stateRequestParameter]; //nil 表示全部数据
}

#pragma mark - getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStyleGrouped)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        //注册cell
        [_tableView registerNib:[UINib nibWithNibName:@"WSOrderCell" bundle:nil] forCellReuseIdentifier:@"WSOrderCell"];
        _tableView.separatorStyle = UITableViewCellEditingStyleNone;
        //隐藏线
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = [UIColor whiteColor]; //背景色
    }
    return _tableView;
}
- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (FDNowDataView *)nodateView {
    if (!_nodateView) {
        _nodateView = [[FDNowDataView alloc] initWithFrame:CGRectMake(0, 60, SCREEN_WIDTH, 300)];
//        _nodateView.hidden = YES; //默认隐藏
    }
    return _nodateView;
}

#pragma mark - 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WSOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WSOrderCell"];
 
    

    //取出model 赋值
    WSOrderModel *model = self.dataArr[indexPath.section];
    cell.wsorderModel = model;
    
    //左侧按钮点击回调 2019-1-22如果这个被触发表示是 @"再来一单"
    cell.clickLeftBtnBlcok = ^(NSNumber *status, NSNumber *paymentType) {
        FDLog(@"点击了左边按钮---处理'再来一单'逻辑");
        [self handleAnotherOrderActionOrderId:model.orderId];
    };
    
    //右边按钮点击回调
    cell.clickRightBtnBlock = ^(NSNumber *status, NSNumber *payType) {
        [self handleButtonsClickLogicWithState:status paymentType:payType orderId:model.orderId];
    };
    return cell;
}


#pragma mark - 线显示效果
//区头线
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *sectionHView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 8)];
    sectionHView.backgroundColor = kMainLightGrayColor;
    
    return sectionHView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 8;
}


//取出 group 样式下多余的部分
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    FDLog(@"点击了section:%ld--row:%ld",indexPath.section,indexPath.row);
}


//!!!!:12-4点击按钮跳
- (void)judgeSkipToWhickVCWithStatus:(NSNumber *)status payType:(NSNumber *)paytype orderModel:(WSOrderModel *)model {

    /**点击按钮的block回调
     tips:
     0 支付；跳转 “支付” 页面
     4 评价 跳转 ”评价“ 页面
     其他都是 “再来一单”  paymentType=1 也是再来一单跳转
     */
    
    if ([status isEqualToNumber:@(0)]) {
        if ([paytype isEqualToNumber:@(1)]) {
            [self skipToZaiLaiYiDanVCWithOrderId:model.orderId];
        }else {
            [self skipToPayUrlVCWithOrderID:model.orderId];
        }
    }else if ([status isEqualToNumber:@(4)]) {
        [self skipToEvaluateVCWithOrderId:model.orderId];
    }else {
        [self skipToZaiLaiYiDanVCWithOrderId:model.orderId];
    }
}

/**立即支付.获取订单支付链接*/
- (void)skipToPayUrlVCWithOrderID:(NSString *)orderId {
    
    [MBProgressHUD fd_showHUDToView:self.view];
    
    [FDHttpAPi requestUserOrderPaymentUrlWithOrderId:orderId successBlock:^(id responseObjc) {
        
        [MBProgressHUD fd_hideHUDFromView:self.view];
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            FDLog(@"%@",responseObjc[@"data"][@"url"]);
            
            WSPayUrlViewController *payurlVC = [[WSPayUrlViewController alloc] init];
            payurlVC.payUrl = responseObjc[@"data"][@"url"];
            [self.navigationController pushViewController:payurlVC animated:YES];
        }
    } fialBlock:^(NSError *error) {
        FDLog(@"%@",[error localizedDescription]);
        
        [MBProgressHUD fd_hideHUDFromView:self.view];
    }];
}
    
- (void)skipToZaiLaiYiDanVCWithOrderId:(NSString *)orderId {
    WSZaiLaiYiDanViewController *zlydVC = [[WSZaiLaiYiDanViewController alloc] init];
    zlydVC.userOrderId = orderId;
    [self.navigationController pushViewController:zlydVC animated:YES];
}

- (void)skipToEvaluateVCWithOrderId:(NSString *)orderId {
    EvaluateController *evaluateVC = [[EvaluateController alloc] init];
    
    evaluateVC.fdDeliveryType = FDDeliveryTypeWaiSong; //配送方式0(外送)
    evaluateVC.userOrderId = orderId;//订单id
    
    [self.navigationController pushViewController:evaluateVC animated:YES];
}
#pragma mark - cell 按钮点击事件2019-1-21
- (void)handleButtonsClickLogicWithState:(NSNumber *)status paymentType:(NSNumber *)payment orderId:(NSString *)orderId{

    //两个按钮
    FDLog(@"前面state 后面payment %@:%@",status,payment);
    
    //0.什么时候显示两个按钮(@"再来一单、评价")
    if ([status isEqualToNumber:@(4)]) {
        [self handleEvalateActionWithOrderId:orderId];
        
        //@“再来一单”
    }else if ([status isEqualToNumber:@(5)] ||
        [status isEqualToNumber:@(6)] ||
        [status isEqualToNumber:@(7)] ||
        [status isEqualToNumber:@(8)] ||
        [status isEqualToNumber:@(9)]) {
        
        [self handleAnotherOrderActionOrderId:orderId]; //处理在来一单
    }
    
    //2019-2-18 再来一单
    if ([payment isEqualToNumber:@(0)] &&
        [status isEqualToNumber:@(3)]) {
        [self handleAnotherOrderActionOrderId:orderId]; //处理在来一单
    }
    
    //2019-2-20 再来一单 status:1/2/3 都是再来一单
    if ([payment isEqualToNumber:@(0)]) {
        if ([status isEqualToNumber:@(1)] ||
            [status isEqualToNumber:@(2)]) {
            [self handleAnotherOrderActionOrderId:orderId];
        }
    }
    
    
    //@“立即支付”
    if ([payment isEqualToNumber:@(0)] &&
        [status isEqualToNumber:@(0)]) {
        [self handlePayNowActionWithState:status paymentType:payment orderId:orderId];
    }
    
    if ([payment isEqualToNumber:@(1)]) {
        if ([status isEqualToNumber:@(0)] ||
            [status isEqualToNumber:@(1)] ||
            [status isEqualToNumber:@(2)] ||
            [status isEqualToNumber:@(3)]) {
            
            [self handlePayNowActionWithState:status paymentType:payment orderId:orderId];
        }
    }
}



//@"评价"按钮事件交互
- (void)handleEvalateActionWithOrderId:(NSString *)orderId {
    FDLog(@"点击了评价按钮");
    [self skipToEvaluateVCWithOrderId:orderId];
}


//再来一单 事件交互
- (void)handleAnotherOrderActionOrderId:(NSString *)orderId {
    [self skipToZaiLaiYiDanVCWithOrderId:orderId];
}


//立即支付事件交互
- (void)handlePayNowActionWithState:(NSNumber *)state paymentType:(NSNumber *)paymentType orderId:(NSString *)orderId{
 
    FDLog(@"点击了立即支付");
    
    //paymentType=0，status=0，点击支付按钮，弹出窗口(线上、线下弹框)
    if ([state isEqualToNumber:@(0)] &&
        [paymentType isEqualToNumber:@(0)]) {
        
        [FDPaytypeAlertTool showAlertTwoPaytypePayOnlineBlock:^{
            [self requestOnlinePayWithOrderId:orderId];
        } offlineBlock:^{
            [self requestOfflinePayWithOrderId:orderId];
        }];
    }
    
    //paymentType=1，status=1、2、3，点击支付按钮，弹出窗口：(在线支付)
    if ([paymentType isEqualToNumber:@(1)]) {
        if ([state isEqualToNumber:@(0)] ||
            [state isEqualToNumber:@(1)] ||
            [state isEqualToNumber:@(2)] ||
            [state isEqualToNumber:@(3)]) {
         
            //一个弹框
            [FDPaytypeAlertTool showAlertOnePayTypeOnlinePayBlock:^{
                [self requestOnlinePayWithOrderId:orderId];
            }];
        }
    }
}


//!!!!:在线支付 弹窗中，点击“在线支付”按钮，调用接口(87号)：/user/order/payment/online
//得到支付“url”连接，展示webview界面，同确认订单部分逻辑
- (void)requestOnlinePayWithOrderId:(NSString *)orderId {
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [FDHttpAPi requestPayOnlineWithOrderId:orderId successBlock:^(id responseObjc) {
        
        [self.hud hideAnimated:YES];
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            //取url
            NSString *url = responseObjc[@"data"][@"url"];
            FDLog(@"url:%@",url);
            //得到支付“url”连接，展示webview界面，同确认订单部分逻辑
            
            WSPayUrlViewController *payurlVC = [[WSPayUrlViewController alloc] init];
            payurlVC.payUrl = url;
            [self.navigationController pushViewController:payurlVC animated:YES];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
        
    } failBlock:^(NSError *error) {
        FDLog(@"线上支付第一步出问题了:%@",[error localizedDescription]);
        [self.hud hideAnimated:YES];
    }];
}

//!!!!:线下支付
//弹窗中，点击“线下支付”按钮，调用接口(88号)：/user/order/payment/offline
//接口调用成功后，刷新当前订单列表即可
- (void)requestOfflinePayWithOrderId:(NSString *)orderId {
    
    [FDHttpAPi requestPayOfflineWithOrderId:orderId successBlock:^(id responseObjc) {
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:SUCCESS]) {
            //刷新列表
//        [self loadOrderDataWithStatus:<#(NSArray<NSNumber *> *)#>]
            [self.tableView.mj_header beginRefreshing];
        }else {
            [JRToast showWithText:responseObjc[describe]];
        }
    } failBlock:^(NSError *error) {
        FDLog(@"线下支付失败:%@",[error localizedDescription]);
    }];
}



#pragma mark - 请求数据
/**子类调用*/
- (void)loadOrderDataWithStatus:(NSArray<NSNumber *> *)status {
    self.stateRequestParameter = status;
    
    FDLog(@"status:%@",status);
    
    //@(0):外送   nil:全部订单
    [FDHttpAPi requestDDOrderListWithDeliveryType:@(0) status:status successBlock:^(id responseObjc) {
        [self.tableView.mj_header endRefreshing]; //结束刷新
        
        NSString *event = responseObjc[@"event"];
        if ([event isEqualToString:@"SUCCESS"]) { //请求成功 解析数据
            NSArray *dataArr = responseObjc[@"data"];
            
            self.nodateView.hidden = NO; //显示没有数据
            
            if(dataArr.count == 0) return ;
            
            self.nodateView.hidden = YES; //隐藏

            [self.dataArr removeAllObjects];
            
            for (NSDictionary *dic in dataArr) {
                WSOrderModel *model = [WSOrderModel mj_objectWithKeyValues:dic];
                [self.dataArr addObject:model];
            }
            //刷新
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }else { //错误处理
            [JRToast showWithText:responseObjc[@"describe"]];
        }
    } failBlock:^(NSError *error) {
       
        [self.tableView.mj_header endRefreshing]; //结束刷新
    }];
}

@end
